﻿using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.IO;
using ICSharpCode.SharpZipLib.Zip;

namespace MCP.FormLoader
{
    [ClassInterface(ClassInterfaceType.AutoDual)]
    public class FormLoaderUpdate
    {
        MCP.FormLoader.Update.AppUpdateService.UpdateApplicationInfo info = new MCP.FormLoader.Update.AppUpdateService.UpdateApplicationInfo();
        MCP.FormLoader.Update.AppUpdateService.UService service = new MCP.FormLoader.Update.AppUpdateService.UService();

        /// <summary>
        /// 判断系统更新
        /// </summary>
        /// 
        public void CheckSystemUpdate()
        {
            try
            {
                string dirPath = GetAssemblyPath();
                string url = getUpdateUrl(dirPath + "appupdateconfig.ini");
                service.Url = url;
                info.AllDataInfo = new MCP.FormLoader.Update.AppUpdateService.DataSetUpdateInfo();
                info.HaveUpdateFiles = false;
                info.NewDataInfo = new MCP.FormLoader.Update.AppUpdateService.DataSetUpdateInfo();
                info.NewFilesInfoBytes = new byte[0];
                
                string localDataFiles = dirPath + "localFileData.dat";
                if (System.IO.File.Exists(localDataFiles))
                {
                    info.AllDataInfo.ReadXml(localDataFiles);
                    info.AllDataInfo.AcceptChanges();
                }
                Boolean res = service.HaveUpdate(info);
                if (res)
                {
                    var result = service.UpdateApplication(info);
                    if (result.HaveUpdateFiles)
                    {
                        byte[] fileInfo = result.NewFilesInfoBytes;
                        DirectoryInfo dir = new DirectoryInfo(dirPath);
                        UNZipFile(result.NewFilesInfoBytes, dir.FullName, dirPath);
                        System.Threading.Thread.Sleep(1000);
                        Process p = new Process();
                        p.StartInfo = new ProcessStartInfo();
                        p.StartInfo.FileName = dirPath + "DocareCPReg.bat";
                        p.StartInfo.Arguments = dir.FullName;
                        p.Start();
                        p.WaitForExit();
                        MessageBox.Show("更新完成,请重新进入系统");
                    }
                    result.AllDataInfo.WriteXml(localDataFiles);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("临床路径更新程序调用失败!\r\n" + ex.StackTrace);
            }
        }


        [ComVisible(false)]
        public Boolean UNZipFile(byte[] fileByte, string targetDirectory,string tmpPath)
        {
            try
            {
                string tmpFile = tmpPath + "tmp.zip";
                FileStream f = new FileStream(tmpFile, FileMode.Create);
                f.Write(fileByte, 0, fileByte.Length);
                f.Close();
                FastZip fastZip = new FastZip();
                fastZip.ExtractZip(tmpFile, targetDirectory, "");
                return true;
            }
            catch
            {
                return false;
            }
        }

        [ComVisible(false)]
        public string GetAssemblyPath()
        {
            string _CodeBase = System.Reflection.Assembly.GetExecutingAssembly().CodeBase;

            _CodeBase = _CodeBase.Substring(8, _CodeBase.Length - 8);    // 8是 file:// 的长度

            string[] arrSection = _CodeBase.Split(new char[] { '/' });

            string _FolderPath = "";
            for (int i = 0; i < arrSection.Length - 1; i++)
            {
                _FolderPath += arrSection[i] + "\\";
            }

            return _FolderPath;
        }


        private string getUpdateUrl(string _configiniPath)
        {

            if (File.Exists(_configiniPath))
            {
                StreamReader sr = new StreamReader(_configiniPath);
                string strContent = sr.ReadLine();
                sr.Close();
                if (!string.IsNullOrEmpty(strContent))
                {
                    return strContent.Trim();
                }
            }
            return "http://localhost:26402/AutoUpdate/UService.asmx";
        }
    }
}